2023/12/234398字符
webpack 配置例子
// webpack 是 node 写出来的
const path = require('path'); // 内置模块
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 外置插件html
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // css
const OpimizeCss = require('optimize-css-assets-webpack-plugin'); // css压缩
module.exports = {
devServer:{ // 开发服务器的配置
port: 3000, // 端口
progress: true, // 滚动条
contentBase: './dist', //
compress: true, // 压缩
open: true, // 自动打开页面
},
mode: 'production', // production development 压缩模式与开发模式
entry: './item/js/demo.js', // 入口
devtool: 'eval-source-map', // 增加映射文件,方便调试代码
/**
* source-map 增加映射文件
* eval-source-map 不会产生文件,但是一个单独的映射文件
* cheap-module-source-map 产生后保留文件
* cheap-module-eval-source-map 不会产生列
*/
watch: false, // 实时打包
watchOptions: { // 监控选项
poll: 1000, // 每秒执行一次
aggregateTimeout: 300, // 防抖
ignored: /node_modules/ // 不需要监控哪个文件
},
output: { // 出口
filename: 'bundle.js', // 打包后的文件名
// filename: 'bundle[hash:8].js', // 加哈希戳只显示8位,防止覆盖打包后的文件名
path: path.resolve(__dirname, 'dist'), // __dirname以当前目录下产生dist目录,路径必须是一个绝对路径
// publicPath: 'http://www.ojbk.com', // 公共路径
},
plugins: [ // 数组 放着所有的webpack插件
new HtmlWebpackPlugin({
template: './item/index.html',
filename: 'index.html',
minify: {
removeAttributeQuotes: true, // 删除双引号
// collapseWhitespace: true, // 折叠空行
removeComments: true, // 移除注释
},
// hash: true, // 是否为引入的js文件添加hash值
inject: true, // 是否通过 js 方式引入 js 文件,对HTML页面引入方式无效
}),
new MiniCssExtractPlugin({
template: './item/css/index.css',
filename: 'index.css',
}),
new OpimizeCss(), // 压缩css代码
],
module: { // 模块
// loader
rules: [ // 规则 css-loader 解析 @import 这种语法
// loader 的顺序默认从右向左执行
{
test: /\.(png|jpg|gif)$/,
use: {
loader: 'url-loader', // 导出图片
options:{
name: '[name].[ext]', // 打包后的图片和原先一致
outputPath: './img',
publicPath: 'http://www.ojbk.com', // 单独公共路径
limit: 20*1024, // 小于20k的图片转为base64,字节不超过1024
}
}
},
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env'
],
plugins: [
'@babel/plugin-proposal-class-properties'
]
}
},
// include: path.resolve(__dirname, item),
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [
// {
// loader: 'style-loader',
// options:{
// insert: 'top', // 嵌入位置,top指顶部,不会覆盖掉html自带的style样式
// minimize: true
// }
// },
MiniCssExtractPlugin.loader,
'css-loader', // 解析css文件
'postcss-loader',
]
},
]
}
}